<template>
  <div>
    <el-collapse :value="defaultActive">

      <!--      分单-->
      <el-collapse-item style="margin-bottom: 10px" name="1" v-if="$permiss[663]">
        <template slot="title">
          <div class="collapse_title">
            {{ $t('分单') }}
          </div>
        </template>
        <div style="width: 500px">
          <el-form :model="orderForm" :rules="orderFormRules" ref="orderForm" label-width="160px">
            <el-form-item :label="$t('资源APP')" prop="resourceApp" v-if="$permiss[664]">
              <el-select v-model="orderForm.resourceApp" @change="resourcesAppSelect" clearable>
                <el-option v-for="item in resourcesProduct" :key="item.productId" :label="item.appName"
                           :value="item.productName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('正常结清时间')">
              <el-date-picker
                  style="width: 100%"
                  value-format="yyyy-MM-dd"
                  v-model="orderForm.timeValue"
                  type="daterange"
                  range-separator="~"
                  :clearable="false"
                  :start-placeholder="$t('开始日期')"
                  :end-placeholder="$t('结束日期')">
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="$t('累计结清合同金额')" prop="settleAmount">
              <el-input v-model.number="orderForm.settleAmount">
                <el-select style="width: 60px" v-model="orderForm.settleAmountSymbol"
                           slot="prepend">
                  <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item :label="$t('结清笔数')" prop="settleNum">
              <el-input v-model.number="orderForm.settleNum">
                <el-select style="width: 60px" v-model="orderForm.settleNumSymbol"
                           slot="prepend">
                  <el-option v-for="item in symbolList" :key="item.label" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item :label="$t('营销APP')" prop="benefitApp" v-if="$permiss[665]">
              <el-select v-model="orderForm.benefitApp" clearable>
                <el-option v-for="item in benefitProduct" :key="item.productId" :label="item.appName"
                           :value="item.productName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchOrder" :loading="searchLoading">{{ $t('查询') }}</el-button>
              <el-button @click="resetForm">{{ $t('重置') }}</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-item>
      <!--      绑定人员-->
      <el-collapse-item style="margin-bottom: 10px" name="2" v-if="$permiss[667]">
        <template slot="title">
          <div class="collapse_title">
            {{ $t('绑定人员') }}
          </div>
        </template>
        <div>
          <el-form label-width="80px">
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item :label="$t('员工姓名')">
                  <el-input v-model="bindPage.adminName" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item :label="$t('账号')">
                  <el-input v-model="bindPage.accountNumber" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="8" style="text-align: right">
                <el-button type="primary" @click="getBindTableData">{{ $t('查询') }}</el-button>
                <el-button @click="clearSearch">{{ $t('重置') }}</el-button>
              </el-col>
            </el-row>
          </el-form>
          <div style="text-align: right;margin-bottom: 10px ">
            <el-button type="primary" v-show="$permiss[648]" @click="addVisible = true,addPersonnelTableData()">{{
                $t('新增')
              }}
            </el-button>
          </div>
          <div style="margin-bottom: 20px">
            <Table :table-column="bindTableColumn" :page="bindPage" :table-data="bingTableData"
                   @handleSizeChange="bingSizeChange"
                   @handleCurrentChange="bingPageChange">
              <template slot="bindApp" slot-scope="{row}">
                <div v-if="row.list && row.list.length">
                  <el-tag :disable-transitions="true" style="margin: 5px 5px 0 0" v-for="item in row.list" :key="item">
                    {{ item }}
                  </el-tag>
                </div>
              </template>
              <template slot-scope="{row}" slot="handle">
                <el-button v-show="$permiss[660]" type="text" @click="handleDelList(row)">{{ $t('解绑') }}</el-button>
              </template>
            </Table>
          </div>
          <!--           新增员工-->
          <Dialog :visible.sync="addVisible" :title="$t('新增')" @confirm="addConfirm" width="45%" :footer="$permiss[651]"
                  @cancel="addVisible = false">
            <el-form label-width="80px">
              <el-row :gutter="24">
                <el-col :span="10">
                  <el-form-item :label="$t('员工姓名')">
                    <el-input v-model="addPage.adminName" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item :label="$t('账号')">
                    <el-input v-model="addPage.accountNumber" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="4" style="text-align: right">
                  <el-button type="primary" @click="addPersonnelTableData">{{ $t('查询') }}</el-button>
                </el-col>
              </el-row>
            </el-form>
            <Table :selection="true" :select-rows="addSelectRows" @handleSelectionChange="handleSelectionChange"
                   :page="false" :table-column="addTableColumn"
                   :table-data="addTableData">
              <template slot="bindApp" slot-scope="{row}">
                <div v-if="row.list && row.list.length">
                  <el-tag :disable-transitions="true" style="margin: 5px 5px 0 0" v-for="item in row.list" :key="item">
                    {{ item }}
                  </el-tag>
                </div>
              </template>
            </Table>
          </Dialog>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!--      查询分单-->
    <Dialog :visible.sync="transferOrderVisible" :title="$t('分单')" :footer="false" width="65%">
      <div style="text-align: right;margin-bottom: 10px">
        <el-button type="primary" @click="distribution('select')">{{ $t('所选分配') }}</el-button>
        <el-button type="primary" @click="distribution('search')">{{ $t('所搜分配') }}</el-button>
      </div>
      <Table :selection="true"
             :loading="loading"
             :select-rows="orderSelectRows" @handleSelectionChange="(val)=>{
            orderSelectRows = val
          }" :table-column="orderTableColumn"
             :table-data="orderTableData" :page="orderPage"
             @handleSizeChange="(val)=>{
               orderPage.pageSize = val
               searchOrder()
             }"
             @handleCurrentChange="(val)=>{
                  orderPage.pageNum = val
                     searchOrder()
             }"
      >
        <template slot="avoidAudit" slot-scope="{row}">
          {{ row.avoidAudit === 1 ? $t('是') : $t('否') }}
        </template>

      </Table>
      <!--         选择营销人员-->
      <Dialog append-body width="45%" :title="distributionTitle" @cancel="distributionPersonVisible = false"
              @confirm="distributionConfirm"
              :visible.sync="distributionPersonVisible" :confirm-loading="confirmLoading">
        <el-form label-width="80px">
          <el-row :gutter="24">
            <el-col :span="10">
              <el-form-item :label="$t('员工姓名')">
                <el-input v-model="distributionPersonPage.adminName" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item :label="$t('账号')">
                <el-input v-model="distributionPersonPage.accountNumber" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button type="primary" @click="getAuditPersonnelSelect">{{ $t('查询') }}</el-button>
            </el-col>
          </el-row>
        </el-form>
        <Table :selection="true" :select-rows="distributionSelectRows" @handleSelectionChange="(val)=>{
            distributionSelectRows = val
          }"
               :page="false" :table-column="distributionTableColumn"
               :table-data="auditPersonnel">
        </Table>
      </Dialog>
    </Dialog>
  </div>
</template>

<script>
import bindList from './bingList'
import {dateFormatSection, defaultTimeDate} from "@/utils/tools";
import {sharedUserConfigQuery, shareUserSelectedSingle, shareUserSearchedSingle, marketBindStaff} from '@/api/marketing'
import {selectMarketingStaff, selectProduct} from '@/api/system'

export default {
  data() {
    return {
      defaultActive: ['1', '2'],
      orderForm: {
        settleNumSymbol: '=',
        settleAmountSymbol: '=',
        timeValue: defaultTimeDate(7)
      },
      orderFormRules: {
        resourceApp: [
          {required: true, message: this.$t('请选择')},
        ],
        benefitApp: [
          {required: true, message: this.$t('请选择')},
        ],
      },
      loading: false,
      resourcesProduct: [],
      bindType: 2,
      symbolList: [
        {label: '>', value: '>'},
        {label: '=', value: '='},
        {label: '≧', value: '>='},
        {label: '≦', value: '<='},
        {label: '<', value: '<'}
      ],
      transferOrderVisible: false,
      orderPage: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      orderTableColumn: [
        {label: this.$t('姓名'), prop: 'name'},
        {label: this.$t('手机号码'), prop: 'phone', minWidth: 120},
        {label: this.$t('身份证号码'), prop: 'idcard', minWidth: 120},
        {label: this.$t('还款时间'), prop: 'refundTime', minWidth: 150},
        {label: this.$t('结清笔数'), prop: 'settleNum'},
        {label: this.$t('APP名称'), prop: 'resourceApp'},
      ],
      orderTableData: [],
      orderSelectRows: [],
      distributionPersonVisible: false,
      distributionPersonPage: {
        pageSize: 1000,
        pageNum: 1,
        total: 0
      },
      distributionSelectRows: [],
      distributionTableColumn: [
        {label: this.$t('员工姓名'), prop: 'adminName'},
        {label: this.$t('账号'), prop: 'accountNumber'},
      ],
      distributionTableData: [],
      distributionType: '',
      distributionTitle: '',
      auditPersonnel: [],
      confirmLoading: false,
      searchLoading: false,
    }
  },
  mixins: [bindList],
  computed: {
    benefitProduct() {
      return this.resourcesProduct.filter(item => item.appName !== this.orderForm.resourceApp)
    }
  },
  created() {
    this.$permiss[664] && this.getResourcesProduct()
  },
  methods: {
    // 查询单
    searchOrder() {
      this.$refs.orderForm.validate(async v => {
        if (v) {

          const {settleNumSymbol, settleAmountSymbol} = this.orderForm
          const [settleStartTime, settleEndTime] = dateFormatSection(this.orderForm.timeValue || [])
          const params = {
            ...this.orderPage,
            ...this.orderForm,
            settleStartTime, settleEndTime,
            settleNumSymbol: settleNumSymbol === '≧' ? '>=' : settleNumSymbol === '≦' ? '<=' : settleNumSymbol,
            settleAmountSymbol: settleAmountSymbol === '≧' ? '>=' : settleAmountSymbol === '≦' ? '<=' : settleAmountSymbol,
          }
          delete params.timeValue
          this.searchLoading = true
          this.loading = true
          const res = await sharedUserConfigQuery(params)
          if (res.code === 1) {
            const {list, total} = res.data
            this.orderTableData = list
            this.orderPage.total=total
            this.searchLoading = false
            this.transferOrderVisible = true
            this.loading = false
          } else {
            this.loading = false
            this.searchLoading = false
          }
        }
      })
    },
    resetForm() {
      this.orderForm = {
        settleNumSymbol: '=',
        settleAmountSymbol: '=',
        timeValue: defaultTimeDate(7)
      }
      this.$refs.orderForm.resetFields()
    },
    distribution(type) {
      if (type === 'select') {
        this.selectDistribution()
      } else if (type === 'search') {
        this.searchDistribution()
      }
    },
    // 所搜分配
    async searchDistribution() {
      await this.getAuditPersonnelSelect()
      this.distributionTitle = this.$t('所搜分配')
      this.distributionType = 'search'
      this.distributionPersonVisible = true
    },
    // 所选分配
    async selectDistribution() {
      await this.getAuditPersonnelSelect()
      this.distributionTitle = this.$t('所选分配')
      this.distributionType = 'select'
      this.distributionPersonVisible = true
    },
    // 获取营销员
    async getAuditPersonnelSelect() {
      const res = await selectMarketingStaff({
        type: 2,
        benefitApp: this.orderForm.benefitApp,
        ...this.distributionPersonPage,
        isRest: 1,
      })
      if (res.code === 1) {
        this.auditPersonnel = res.data
      }
    },
    // 开始分单
    async distributionConfirm() {
      if (this.distributionSelectRows.length === 0) return this.$message.error(this.$t('请选择营销员'))
      const auditList = this.distributionSelectRows.map(item => item.adminUserId)
      const orderRows = this.orderSelectRows.map(item => item.userId)
      const [settleStartTime, settleEndTime] = dateFormatSection(this.orderForm.timeValue || [])
      let params = {}
      if (this.distributionType === 'search') {
        // 所搜分配
        params = {
          marketingUserIds: auditList,
          ...this.orderForm,
          settleStartTime, settleEndTime,
        }
      } else {
        // 所选分配
        if (this.orderSelectRows.length === 0) {
          this.confirmLoading = false
          return this.$message.error(this.$t('请勾选要分配的订单'))
        }
        params = {
          ...this.orderForm,
          settleStartTime, settleEndTime,
          ids: orderRows,
          marketingUserIds: auditList
        }
      }
      delete params.timeValue
      this.confirmLoading = true
      const api = (params) => this.distributionType === 'search' ? shareUserSearchedSingle(params) : shareUserSelectedSingle(params)
      const res = await api(params)
      if (res.code === 1) {
        this.confirmLoading = false
        this.distributionPersonVisible = false
        this.searchOrder()
        this.$message.success(this.$t('操作成功'))
      } else {
        this.confirmLoading = false
      }
    },

    resourcesAppSelect(value) {
      if (this.orderForm.benefitApp) this.orderForm.benefitApp = null
    },
    //  获取资源APP
    async getResourcesProduct() {
      const res = await selectProduct()
      if (res.code === 1) {
        this.resourcesProduct = res.data
      }
    },

  }
}
</script>

<style scoped>
.collapse_title {
  margin-left: 20px;
  font-size: 16px;
}

>>> .el-collapse-item__header {
  background-color: #FFF4D3;
}

>>> .el-collapse-item__content {
  padding: 20px 20px 0 20px;
}
</style>
